/**
 *  通知native调用appCommand接口
 *  @returns {*}
 */
invokeNative('do_js_finish');
/**
 *  向原生开放接口
 *  @returns {*}
 */
function appCommand(msg) {

    $(function () {

        if (JSON.parse(msg).jcmd === 'return_uid') {
            window.auth = JSON.parse(msg).data.auth;
            var isTap = true,
                flag = true,
                timer = '';
            var refresh = $('#refresh'),
                charge = $('#chargeBtn');
            // 初始化数据
            reFresh(auth);
            // 点击刷新
            refresh.on('tap', function () {
                if(flag){
                    reFresh(auth, isTap);
                    flag = false;
                    timer = setTimeout(function () {
                        clearTimeout(timer);
                        flag = true;
                    },3000);
                } else {
                    invokeNative('show_toast','3s后操作')
                }
            });
        }

        /* 指令刷新 */
        if (JSON.parse(msg).jcmd === 'refresh_web') {
            reFresh(window.auth);
        }

        // 点击支付事件
        charge.on('tap', function () {
            invokeNative('do_pay');
        });

        // 禁用禁用长按弹出菜单
        $('body').on('contextmenu', function(e) {
            e.preventDefault();
        })

    });

}


// ------- 刷新 获取最新数据函数 -------
function reFresh(oth,isTap) {
    if (oth) {
        var chargeUrl = 'http://api.yanyuan01.cn/v1/sys_activity/get_now',
            awardUrl = 'http://api.yanyuan01.cn/v1/rec_activity/get_all',
            spellsUrl = 'http://api.yanyuan01.cn/v1/sys_activity/get_day',
            auth = {'auth': oth};
        window.sendTM = new Date().getTime();

        // ------- 获取/渲染 该时间段奖品 -------
        getTimeInfo(spellsUrl, auth, isTap);

        // ------- 获取/渲染 充值信息列表 -------
        getChargeInfo(chargeUrl, auth);

        // ------- 获取/渲染 获奖信息列表 -------
        getAwardInfo(awardUrl, auth);

    } else {
        invokeNative('show_toast', '数据获取失败')
    }
}


// ------- 获取/渲染 TimeLine & prize -------
function getTimeInfo(url, auth, isTap) {

    var swipeWrapper = $('.swiper-wrapper'),
        prize = $('.prize'),
        timerWrapper = $('#timer-wrapper'),
        overTime = $('.overTime-wrapper');

    getInfo(url, auth, function (data) {


        // 状态为 Error 时 提示无活动
        if (data.status === 'ERROR') {
            prize.empty().append('<img src="images/未完待续.jpg" style="width: 100%;height: 100%;"/>');
            $('.chargeInfo').empty().append('<section class="eachChargeInfo" style="height: 100%;justify-content: center;align-items: center;font-size: 0.3rem;"><p></p><p>今天没有活动</p><p></p></section>');
            return;
        }

        if (data.status === 'OK') {
            window.getTM = new Date().getTime();

            // 手动刷新 提示成功
            if(isTap){
                invokeNative('show_toast','刷新成功')
            }

            // ------- 一天只有一个活动 -------
            if (data.res.length === 1) {

                var _startTime = data.res[0].StartTime.substr(0, 19).replace('T', ' ').replace(/-/g, '/').split(' ')[1].slice(0, 5),
                    _endTime = data.res[0].EndTime.substr(0, 19).replace('T', ' ').replace(/-/g, '/').split(' ')[1].slice(0, 5);
                var startStr = new Date(data.res[0].StartTime.split('+')[0].replace('T', ' ').replace(/-/g, '/')).getTime(),
                    endStr = new Date(data.res[0].EndTime.split('+')[0].replace('T', ' ').replace(/-/g, '/')).getTime();
                var duringOne = parseInt((endStr-startStr)/1000);

                var _Html = '<div class="swiper-slide">' +
                    '   <div class="item">' +
                    '       <img src="" alt="" class="location">' +
                    '       <p class="character "></p>' +
                    '       <span class="acTime ">' + _startTime + '-' + _endTime + '</span>' +
                    '   </div>' +
                    '</div>';

                // ------- 活动时间 --------
                $('#time-quantum').html(_startTime + '-' + _endTime);
                // ------- 活动礼品 -------
                prize.attr('src', data.res[0].GoodsImg);
                // ------- 时间轴 --------
                swipeWrapper.empty().append(_Html);
                // ------- 初始滑动轮播 -------
                var _swiper = new Swiper('.swiper-container', {
                    slidesPerView: 1,
                    spaceBetween: 30,
                    initialSlide: 0
                });
                // ------- TimeLine样式 -------
                // 活动 已结束
                if (data.res[0].CountDownTime < 0) {
                    prize.empty().append('<img src="images/未完待续.jpg" style="width: 100%;height: 100%;"/>');
                    $('.swiper-slide').find('.character').text('活动已结束').addClass('bgColor-gray')
                        .siblings('.location').attr('src', 'images/限时充值_07.png')
                        .siblings('.acTime').addClass('color-gray');
                    // 活动 未开始
                } else if (data.res[0].CountDownTime > duringOne) {
                    prize.empty().append('<img src="images/未完待续.jpg" style="width: 100%;height: 100%;"/>');
                    $('.swiper-slide').find('.character').text('活动未开始').addClass('bgColor-orange')
                        .siblings('.location').attr('src', 'images/限时充值_08.png')
                        .siblings('.acTime').addClass('color-orange');
                    // 活动 进行中
                } else {
                    $('.acTime').addClass('color-red')
                        .siblings('.character').text('活动进行中').addClass('bgColor-red')
                        .siblings('.location').attr('src', 'images/限时充值_09.png');
                    // ------- 倒计时 -------
                    fnTimeCountDown(endStr);
                }

            } else if (data.res.length > 1) {

                var html = '',
                    now = (data.tm)*1000,
                    activeStartTime = data.res[0].StartTime.split('T')[1].split('+')[0].slice(0, 5),
                    activeEndTime = data.res[data.res.length - 1].EndTime.split('T')[1].split('+')[0].slice(0, 5)/*,
                    startTimeStr = new Date(data.res[1].StartTime.toString().split('+')[0].toString().replace('T', ' ').replace(/-/g, '/')).getTime(),
                    endTimeStr = new Date(data.res[1].EndTime.toString().split('+')[0].toString().replace('T', ' ').replace(/-/g, '/')).getTime();

                var during = parseInt((endTimeStr-startTimeStr)/1000)*/;

                // ------- 添加 时间轴 --------
                for (var i = 0; i < data.res.length; i++) {

                    // 各个时间段
                    html += '<div class="swiper-slide">' +
                        '   <div class="item">' +
                        '       <img src="" alt="" class="location">' +
                        '       <p class="character "></p>' +
                        '       <span class="acTime " data-start="'+data.res[i].StartTime.replace('T',' ').split('+')[0].replace(/-/g,'/')+'" data-end="'+data.res[i].EndTime.replace('T',' ').split('+')[0].replace(/-/g,'/')+'">' +
                        (data.res[i].StartTime.split('T')[1].split('+')[0].slice(0, 5)) + '-' + (data.res[i].EndTime.split('T')[1].split('+')[0].slice(0, 5)) +
                        '       </span>' +
                        '   </div>' +
                        '</div>';

                }

                swipeWrapper.empty().append(html);

                // ------- 活动说明 活动时间 --------
                $('#time-quantum').empty().html(activeStartTime + '-' + activeEndTime);

                // ------- 本期礼品 --------
                var acTimes = document.getElementsByClassName('acTime'),
                    swipers = document.getElementsByClassName('swiper-slide');

                if(now < new Date($(acTimes[0]).attr('data-start')).getTime()){
                    // 今日活动未开始
                    prize.empty().append('<img src="images/未完待续.jpg" style="width: 100%;height: 100%;"/>');
                    for(var i=0;i<acTimes.length;i++){
                        $(acTimes[i]).addClass('color-orange')
                            .siblings('.character').text('活动未开始').addClass('bgColor-orange')
                            .siblings('.location').attr('src', 'images/限时充值_08.png');
                    }
                    var allReadySwiper = new Swiper('.swiper-container', {
                        slidesPerView: 3,
                        spaceBetween: 30,
                        initialSlide: 0
                    });
                    timerWrapper.empty();
                        overTime.empty();
                    return;
                }else if(now >= new Date($(acTimes[acTimes.length-1]).attr('data-end')).getTime()){
                    // 今日活动已结束
                    prize.empty().append('<img src="images/未完待续.jpg" style="width: 100%;height: 100%;"/>');
                    for(var j=0;j<acTimes.length;j++){
                        $(acTimes[j]).addClass('color-gray')
                            .siblings('.character').text('活动已结束').addClass('bgColor-gray')
                            .siblings('.location').attr('src', 'images/限时充值_07.png');
                    }
                    var allDoneSwiper = new Swiper('.swiper-container', {
                        slidesPerView: 3,
                        spaceBetween: 30,
                        initialSlide: swipers.length - 1
                    });
                    timerWrapper.empty();
                    overTime.hide().empty();
                    return;
                }else{
                    // 今日活动中
                    for(var k = 0; k < acTimes.length; k++ ){
                        var acTime = $(acTimes[k]),
                            swiper = $(swipers[k]),
                            actStart = new Date($(acTimes[k]).attr('data-start')).getTime(),
                            actEnd = new Date($(acTimes[k]).attr('data-end')).getTime(),
                            nextActStart = new Date($(acTimes[k+1]).attr('data-start')).getTime();
                        // 进行中
                        if(now>=actStart && now<actEnd){
                            prize.empty().append('<img src="' + data.res[k].GoodsImg + '" style="width: 100%;height: 100%;"/>');
                            // 添加 活动加时
                            var addTime = Number(data.res[k].ActivityAdd);
                            if(addTime && addTime>0){
                                overTime.show();
                                overTime.html('加时<span id="overTime">'+addTime+'</span>分钟');
                            }else{
                                overTime.hide();
                            }
                            var mySwiper = new Swiper('.swiper-container', {
                                slidesPerView: 3,
                                spaceBetween: 30,
                                initialSlide: k - 1
                            });

                            // 当前活动中样式
                            acTime.addClass('color-red')
                                .siblings('.character').text('活动进行中').addClass('bgColor-red')
                                .siblings('.location').attr('src', 'images/限时充值_09.png');
                            // 活动结束样式
                            swiper.prevAll('.swiper-slide').find('.character').text('活动已结束').addClass('bgColor-gray')
                                .siblings('.location').attr('src', 'images/限时充值_07.png')
                                .siblings('.acTime').addClass('color-gray');
                            // 活动未开始部分样式
                            swiper.nextAll('.swiper-slide').find('.character').text('活动未开始').addClass('bgColor-orange')
                                .siblings('.location').attr('src', 'images/限时充值_08.png')
                                .siblings('.acTime').addClass('color-orange');

                            // 调用倒计时函数
                            fnTimeCountDown(parseInt((actEnd-now)/1000));
                            return;
                        }else if(nextActStart && now>=actEnd && now<nextActStart){
                            // 休息中
                            prize.empty().append('<img src="images/未完待续.jpg" style="width: 100%;height: 100%;"/>');
                            // 结束部分
                            acTime.addClass('color-gray')
                                .siblings('.character').text('活动已结束').addClass('bgColor-gray')
                                .siblings('.location').attr('src', 'images/限时充值_07.png');
                            // 结束部分
                            swiper.prevAll('.swiper-slide').find('.character').text('活动已结束').addClass('bgColor-gray')
                                .siblings('.location').attr('src', 'images/限时充值_07.png')
                                .siblings('.acTime').addClass('color-gray');
                            // 未开始部分
                            swiper.nextAll('.swiper-slide').find('.character').text('活动未开始').addClass('bgColor-orange')
                                .siblings('.location').attr('src', 'images/限时充值_08.png')
                                .siblings('.acTime').addClass('color-orange');
                            timerWrapper.empty();
                            overTime.hide().empty();
                        }
                    }
                }
            }

        }

    });
}


// ------- 获取/渲染 充值信息列表 -------
function getChargeInfo(url, auth) {

    getInfo(url, auth, function (data) {

        var html = '',
            payInfo = $('.chargeInfo');

        if (data.status === 'ERROR') {
            payInfo.empty().append('<section class="eachChargeInfo" style="height: 100%;justify-content: center;align-items: center;font-size: 0.3rem;"><p></p><p>暂无活动</p><p></p></section>');
            return;
        }

        if (data.status === 'OK') {

            // 如果没有充值排名信息 显示活动正在进行中
            if (data.res.Rank === null || data.res.Rank.length === 0) {

                payInfo.empty().append('<section class="eachChargeInfo" style="height: 100%;justify-content: center;align-items: center;font-size: 0.3rem;"><p></p><p>活动进行中...</p><p></p></section>');

            } else {

                // 拼接html
                var myInfo = '<section class="myCharge"><p class="width-40">我的充值</p><p class="width-30">' + data.res.Amount + '元</p><p class="width-30">' + data.res.PayTime.split('+')[0].toString().split('T')[1].split('.')[0] + '</p></section>';

                for (var j = 0; j < data.res.Rank.length; j++) {
                    var CNickName = jEmoji.softbankToUnified(data.res.Rank[j].NickName.replace(/\s+/g,"").replace(/\n/g, '<br/>')),
                        CRank = data.res.Rank[j].Rank,
                        CAmount = data.res.Rank[j].Amount,
                        CPayTime = data.res.Rank[j].PayTime.split('+')[0].toString().split('T')[1].split('.')[0];

                    html += '<section class="eachChargeInfo"><p class="width-40"><span class="block">第' + transition(CRank) + '名 (</span><span class="block over">' + CNickName + '</span><span class="block">)</span></p><p class="width-30">' + CAmount + '元</p><p class="width-30">' + CPayTime + '</p></section>';

                }

                // 渲染数据
                payInfo.empty().append(myInfo + html);

            }
        }

    });

}


// ------- 获取/渲染 获奖信息列表 -------
function getAwardInfo(url, auth) {

    getInfo(url, auth, function (data) {
        var str = '',
            awardInfo = data.res;

        if (data.status === 'ERROR') return;

        if (awardInfo === null || awardInfo.length === 0) {

            $('.award-record').empty().append('<div style="width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;">暂无奖品记录</div>');

        } else {

            for (var k = 0; k < awardInfo.length; k++) {
                var ANickName = jEmoji.softbankToUnified(awardInfo[k].NickName.replace(/\s+/g,"").replace(/\n/g, '<br/>')),
                    AGoods = awardInfo[k].GoodsTitle,
                    AStartTime = awardInfo[k].StartTime.toString().split('T')[1].slice(0, 5),
                    AEndTime = awardInfo[k].EndTime.toString().split('T')[1].slice(0, 5),
                    AAid = awardInfo[k].Aid;

                str += '<div class="user-award-info"><p class="userName"><span>' + ANickName + '</span></p>用户获得了<p class="what"><span>' + AGoods + '</span></p><p><span class="winHour" style="padding-right: 1px;">' + AStartTime + '</span>-<span class="winMin">' + AEndTime + '</span></p><p class="detailBtn color-red" data-aid="' + AAid + '">详情...</p></div>';
            }

            $('.award-record').empty().append(str);

        }

        autoScroll();
        getDetail(auth);
    });

}


// ------- 详情模态窗口 -------
function getDetail(Auth) {

    var auth = Auth.auth;

    // 获取某段时间的充值详情
    $('.award-record').on('tap', '.detailBtn', function () {

        var detailStr = '',
            aid = $(this).attr('data-aid'),
            detailUrl = 'http://api.yanyuan01.cn/v1/rec_activity/get';
        var params = {
            auth: auth,
            aid: aid
        };
        var modal = $('#modal'),
            detailWrapper = $('.details-wrapper');

        getInfo(detailUrl, params, function (data) {

            for (var i = 0; i < data.res.length; i++) {

                var hour = data.res[i].PayTime.split('T')[1].toString().split('+')[0].toString().split(':')[0],
                    min = data.res[i].PayTime.split('T')[1].toString().split('+')[0].toString().split(':')[1],
                    sec = data.res[i].PayTime.split('T')[1].toString().split('+')[0].toString().split(':')[2];

                var nickName = jEmoji.softbankToUnified(data.res[i].NickName.replace(/\s+/g,"").replace(/\n/g, '<br/>')),
                    rank = data.res[i].Rank,
                    amount = data.res[i].Amount;
                detailStr += '<section class="personal-pay">' +
                    '  <p class="width-44 text-left">' +
                    '      <span>第' + transition(rank) + '名</span>(<span class="modalUser">' + nickName + '</span>)' +
                    '  </p>' +
                    '  <p class="width-20 paddingLeft-10 text-left">' +
                    '      <span>' + amount + '</span>元' +
                    '  </p>' +
                    '  <p class="width-30">' +
                    '      <span>' + hour + '</span>:<span>' + min + '</span>:<span>' + sec + '</span>' +
                    '   </p>' +
                    '</section>';

            }

            // 模态添加 充值详情
            detailWrapper.empty().append(detailStr);
            modal.show();

            // 关闭弹窗
            $('#close').on('click',function () {
                detailWrapper.empty();
                modal.hide();
            });
            $('body').on('tap', function (event) {
                var e = event || window.event;
                if (e.target === modal[0]) {
                    detailWrapper.empty();
                    modal.hide();
                }
            })
        })

    });

}
